<script setup lang="ts">
import type { VideoPlayerProps } from './helpers'
import {
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  unref,
  useAttrs,
  watch,
} from 'vue'
import Player from 'xgplayer'
import DashPlugin from 'xgplayer-dash'
import FlvPlugin from 'xgplayer-flv'
import HlsPlugin from 'xgplayer-hls'
import 'xgplayer/dist/index.min.css'

const props = withDefaults(defineProps<VideoPlayerProps>(), {
  lang: 'zh-cn',
})

const attrs = useAttrs()

const playerRef = ref<Player>()

const videoEl = ref<HTMLDivElement>()

function intiPlayer() {
  if (!unref(videoEl))
    return
  const enhanceConfig: Record<string, any> = {}
  if (props.autoplay || props.autoplayMuted) {
    enhanceConfig.autoplay = true
    enhanceConfig.autoplayMuted = true
  }
  const plugins = props.plugins ?? (props.type == 'flv'
    ? [FlvPlugin]
    : props.type == 'hls'
      ? [HlsPlugin]
      : props.type == 'dash'
        ? [DashPlugin]
        : undefined)
  playerRef.value = new Player({
    ...props,
    ...attrs,
    ...enhanceConfig,
    plugins,
    el: unref(videoEl),
  })
}

onMounted(() => {
  intiPlayer()
})

watch(
  () => props,
  async (newProps) => {
    await nextTick()
    if (newProps) {
      unref(playerRef)?.setConfig(newProps)
    }
  },
  {
    deep: true,
  },
)

onBeforeUnmount(() => {
  unref(playerRef)?.destroy()
})

defineExpose({
  playerExpose: () => unref(playerRef),
})
</script>

<template>
  <div ref="videoEl" />
</template>
